<?php

namespace Haozing\FastCore\Exception\Handler;

use Haozing\FastCore\Log\RequestIdHolder;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Qbhy\HyperfAuth\Exception\UnauthorizedException;
use Throwable;

class AuthExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {

        $this->stopPropagation();

        $data = [
            'code' => $throwable->getCode(),
            'message' => $throwable->getMessage(),
            'data' => []
        ];
        $data['requestId'] = RequestIdHolder::getId();
        $dataStream = new SwooleStream(json_encode($data, JSON_UNESCAPED_UNICODE));
        ## 阻止异常冒泡
        $this->stopPropagation();
        return $response->withHeader('Server', 'fast-core')
            ->withAddedHeader('Content-Type', 'application/json;charset=utf-8')
            ->withStatus(200)
            ->withBody($dataStream);
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof UnauthorizedException;
    }
}